package com.zenq.ssm.web.ctrl;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zenq.ssm.entity.User;
import com.zenq.ssm.service.UserService;
import com.zenq.ssm.utils.WebAppUtil;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
//	@RequestMapping("/to_reg")
//	public String toreg() {
//		// 进行一些业务逻辑的处理
//		return "reg";
//	}
	
	@RequestMapping("/reg")
	public ModelAndView regist(@ModelAttribute User user) {
		ModelAndView mav = new ModelAndView();
		boolean result = userService.regist(user);
		// 可以自行补充逻辑.......
		if (result) {
			// 表示注册成功(使用重定向，解决刷新页面，重复提交表单的问题)
			mav.setViewName("redirect:/tologin");
		} else {
			//注册失败
			// prefix + viewName + suffix
			mav.setViewName("user/cart");//需要返回到注册页面........
		}
		// 给与客户端响应消息
		// 如果想要将数据传递到View，
		// Request.setAttribute()
		// SpringMVC --> ModelAndView
		mav.addObject("reg_result", result);
		return mav;
	}
	
	@RequestMapping("/login")
	public ModelAndView login(@ModelAttribute User user) {
		ModelAndView mav = new ModelAndView();
		User loginUser = userService.login(user);
		System.out.println(loginUser);
		//将当前登录用户信息存入Session作用域
		HttpSession session = WebAppUtil.getSession();
		session.setAttribute("loginUser", loginUser);
		mav.setViewName("redirect:/p/list");
		return mav;
	}
}
